package com.example.audio_data;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;

import java.util.Arrays;

public class AudioRecorderThread extends Thread{

    //采样率
    private static final int SAMPLE_RATE = 44100;
    //单声道
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
    //音频数据的编码格式
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    //音频数据缓冲区的大小
    private static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);

    private AudioRecord audioRecord;
    private boolean isRecording = false;

    private Handler handler;

    public AudioRecorderThread(Handler handler){
        this.handler = handler;
    }

    @Override
    public void run() {
        super.run();

        System.out.println("缓冲区大小为 " + BUFFER_SIZE);
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT, BUFFER_SIZE);

        byte[] buffer = new byte[BUFFER_SIZE];
        audioRecord.startRecording();

        isRecording = true;
        while (isRecording) {
            int bytesRead = audioRecord.read(buffer, 0, BUFFER_SIZE);

            // 将音频数据传递给Flutter应用程序
            //AudioDataPlugin.sendAudioData(buffer, bytesRead);
//            System.out.println("音频数据：" + Arrays.toString(buffer));
            Message message = this.handler.obtainMessage(0,buffer);
            this.handler.sendMessage(message);
        }
    }

    public void stopRecording() {
        isRecording = false;
        audioRecord.stop();
        audioRecord.release();
    }
}
